/**
 * File    : AuditableListener.java
 * Created : 2008-9-25
 * By      : LuHuiguo
 */
package com.luhuiguo.sso.entity;

import java.util.Date;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;


/**
 * @author LuHuiguo
 * @version $Id: AuditableListener.java 16 2008-10-17 13:13:27Z LuHuiguo $
 *
 */
public class AuditableListener {

	public String getUsername() {
		if ((SecurityContextHolder.getContext() == null)
				|| !(SecurityContextHolder.getContext() instanceof SecurityContext)
				|| (((SecurityContext) SecurityContextHolder.getContext())
						.getAuthentication() == null)) {
			return null;
		}
		return ((SecurityContext) SecurityContextHolder.getContext())
				.getAuthentication().getName();

	}

	@PrePersist
	public void onAuditableEntityPrePersist(Auditable e) {
		Date now = new Date();
		e.setCreator(getUsername());
		e.setCreateDate(now);
		e.setModifier(getUsername());
		e.setModifyDate(now);
	}

	@PreUpdate
	public void onAuditableEntityPreUpdate(Auditable e) {
		Date now = new Date();
		e.setModifier(getUsername());
		e.setModifyDate(now);
	}	
	
	
}
